from django.db.models.signals import post_save, post_delete, post_migrate
from django.dispatch import receiver
from django.contrib.auth.models import Permission as DjangoPermission, Group as DjangoGroup
from django.core.cache import cache
from .models import PermissionExtension, RoleExtension, UserRoleAssignment


@receiver(post_migrate)
def create_missing_extensions(sender, **kwargs):
    """在migrate后检查并创建缺失的权限扩展和角色扩展"""
    # 只在permissions应用的migrate后执行
    if sender.name == 'apps.permissions':
        print("🔍 检查缺失的权限扩展和角色扩展...")

        # 1. 创建缺失的权限扩展
        existing_perm_ids = PermissionExtension.objects.values_list('permission_id', flat=True)
        missing_perms = DjangoPermission.objects.exclude(id__in=existing_perm_ids)

        perm_created_count = 0
        for perm in missing_perms:
            # 从权限代码名推断模块信息
            codename_parts = perm.codename.split('_')
            if len(codename_parts) >= 2:
                action = codename_parts[0]  # add, change, delete, view
                model_name = '_'.join(codename_parts[1:])
                module = perm.content_type.app_label
            else:
                action = perm.codename
                model_name = perm.content_type.model
                module = perm.content_type.app_label

            # 创建权限扩展
            ext, created = PermissionExtension.objects.get_or_create(
                permission=perm,
                defaults={
                    'module': module,
                    'resource_path': f'/{module}/{model_name}/',
                    'api_endpoint': f'/api/{module}/{model_name}/',
                    'description': perm.name,
                    'status': 'active'
                }
            )

            if created:
                perm_created_count += 1

        # 2. 创建缺失的角色扩展
        existing_group_ids = RoleExtension.objects.values_list('group_id', flat=True)
        missing_groups = DjangoGroup.objects.exclude(id__in=existing_group_ids)

        role_created_count = 0
        for group in missing_groups:
            # 从组名生成角色代码
            code = group.name.lower().replace(' ', '_').replace('-', '_')

            # 创建角色扩展
            role_ext, created = RoleExtension.objects.get_or_create(
                group=group,
                defaults={
                    'code': code,
                    'description': f'角色: {group.name}',
                    'status': 'active',
                    'is_system': False
                }
            )

            if created:
                role_created_count += 1

        # 输出结果
        if perm_created_count > 0:
            print(f"✅ 自动创建了 {perm_created_count} 个权限扩展")
        else:
            print("📋 所有权限扩展都已存在")

        if role_created_count > 0:
            print(f"✅ 自动创建了 {role_created_count} 个角色扩展")
        else:
            print("📋 所有角色扩展都已存在")


@receiver(post_save, sender=DjangoPermission)
def create_permission_extension(sender, instance, created, **kwargs):
    """当创建Django权限时，自动创建权限扩展"""
    if created:
        # 从权限代码名推断模块信息
        codename_parts = instance.codename.split('_')
        if len(codename_parts) >= 2:
            action = codename_parts[0]  # add, change, delete, view
            model_name = '_'.join(codename_parts[1:])
            module = instance.content_type.app_label
        else:
            action = instance.codename
            model_name = instance.content_type.model
            module = instance.content_type.app_label

        # 创建权限扩展
        PermissionExtension.objects.get_or_create(
            permission=instance,
            defaults={
                'module': module,
                'resource_path': f'/{module}/{model_name}/',
                'api_endpoint': f'/api/{module}/{model_name}/',
                'description': instance.name,
                'status': 'active'
            }
        )


@receiver(post_save, sender=DjangoGroup)
def create_role_extension(sender, instance, created, **kwargs):
    """当创建Django组时，自动创建角色扩展"""
    if created:
        # 从组名生成角色代码
        code = instance.name.lower().replace(' ', '_').replace('-', '_')
        
        # 创建角色扩展
        RoleExtension.objects.get_or_create(
            group=instance,
            defaults={
                'code': code,
                'description': f'角色: {instance.name}',
                'status': 'active',
                'is_system': False
            }
        )


@receiver(post_save, sender=UserRoleAssignment)
@receiver(post_delete, sender=UserRoleAssignment)
def clear_user_permissions_cache(sender, instance, **kwargs):
    """当用户角色分配发生变化时，清除用户权限缓存"""
    cache_key = f'user_permissions:{instance.user.id}'
    cache.delete(cache_key)
    
    # 也清除用户相关的其他缓存
    cache.delete(f'user_roles:{instance.user.id}')
    cache.delete(f'user_groups:{instance.user.id}')


@receiver(post_save, sender=RoleExtension)
def clear_role_permissions_cache(sender, instance, **kwargs):
    """当角色权限发生变化时，清除相关缓存"""
    # 清除角色权限缓存
    cache_key = f'role_permissions:{instance.id}'
    cache.delete(cache_key)
    
    # 清除该角色下所有用户的权限缓存
    user_assignments = UserRoleAssignment.objects.filter(
        role=instance, 
        status='active'
    ).select_related('user')
    
    for assignment in user_assignments:
        user_cache_key = f'user_permissions:{assignment.user.id}'
        cache.delete(user_cache_key)


def clear_all_permissions_cache():
    """清除所有权限相关缓存的工具函数"""
    # 这个函数可以在权限系统发生重大变更时调用
    # 例如：在管理后台批量修改权限时
    
    # 获取所有用户ID
    from django.contrib.auth import get_user_model
    User = get_user_model()
    
    user_ids = User.objects.values_list('id', flat=True)
    
    # 清除所有用户权限缓存
    for user_id in user_ids:
        cache.delete(f'user_permissions:{user_id}')
        cache.delete(f'user_roles:{user_id}')
        cache.delete(f'user_groups:{user_id}')
    
    # 清除所有角色权限缓存
    role_ids = RoleExtension.objects.values_list('id', flat=True)
    for role_id in role_ids:
        cache.delete(f'role_permissions:{role_id}')
    
    print("已清除所有权限相关缓存")
